package com.example.sampleeventtest;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyView extends View {
	Path mFingerDrawPath;
	float mOldX, mOldY;
	boolean isDowned  = false;
	Paint mPaint, mOffScreenPaint;
	Bitmap offscreenBitmap;
	Canvas offScreenCanvas;
	
	public MyView(Context context) {
		this(context, null, 0);
		// TODO Auto-generated constructor stub
	}

	public MyView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public MyView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mFingerDrawPath = new Path();
		mPaint = new Paint();
		mOffScreenPaint = new Paint();
		mOffScreenPaint.setStyle(Paint.Style.STROKE);
		mOffScreenPaint.setStrokeWidth(10);
		mOffScreenPaint.setColor(Color.BLACK);
		
		// TODO Auto-generated constructor stub
	}
	
	
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int width= getMeasuredWidth();
		int height = getMeasuredHeight();
		
		if(offscreenBitmap == null || (offscreenBitmap.getWidth() != width || offscreenBitmap.getHeight() !=height)){
			Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
			offScreenCanvas = new Canvas(bm);
			if (offscreenBitmap != null){
				offScreenCanvas.drawBitmap(offscreenBitmap, 0, 0, mPaint);
				offscreenBitmap.recycle();
			}
			offscreenBitmap = bm;
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawColor(Color.WHITE);
		canvas.drawBitmap(offscreenBitmap, 0, 0, mPaint);
//		canvas.drawPath(mFingerDrawPath, mPaint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		float x = event.getX();
		float y = event.getY();
		
		switch (action) {		
		case MotionEvent.ACTION_DOWN:
			isDowned = true;
			mOldX = x;
			mOldY = y;
			mFingerDrawPath.moveTo(x, y);
			return true;
		case MotionEvent.ACTION_MOVE:
			if (isDowned){
//				mFingerDrawPath.lineTo(x, y);
				if (offScreenCanvas != null){
					offScreenCanvas.drawLine(mOldX, mOldY, x, y, mOffScreenPaint);
					mOldX =x;
					mOldY = y;
					invalidate();
				}
				return true;
			}
			break;
		case MotionEvent.ACTION_UP:
			isDowned = false;
			break;

		default:
			break;
		}
		return super.onTouchEvent(event);
	}
	

}
